package dao;

import text.UserBean;
import utils.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class RegisterDao {

    public static boolean registerDao(UserBean user) {
        Connection conn = null;
        PreparedStatement ps = null;
        PreparedStatement ps_1 = null;
        ResultSet rs_1 = null;

        //如果注册的用户名或密码存在空以及使用空格的情况不允许注册
        if (user.getUsername() == "" || user.getPassword() == "")
            return false;

        if (user.getUsername() != null && user.getPassword() != null) {
            try {
                //连接数据库
                conn = JDBCUtil.getConnection();
                conn.setAutoCommit(false);

                //在数据库中增加用户名和密码
                String sql = "insert into user values(null, ?, ?)";
                //防止用户名相同的情况
                String sql_1 = "select * from user where username = ?";
                ps = conn.prepareStatement(sql);
                ps_1 = conn.prepareStatement(sql_1);
                //将参数加载进sql语句里
                ps.setString(1, user.getUsername());
                ps.setString(2, user.getPassword());

                ps_1.setString(1, user.getUsername());
                //查询是否有用户名相同情况，有则不允许，返回false
                rs_1 = ps_1.executeQuery();
                if (rs_1.next())
                    return false;

                int cnt = ps.executeUpdate();
                conn.commit();
                if (cnt > 0)
                    return true;
            } catch (SQLException e) {
                if (conn != null) {
                    try {
                        conn.rollback();
                    } catch (SQLException ex) {
                        ex.printStackTrace();
                    }
                }
                e.printStackTrace();
                return false;
            } finally {
                JDBCUtil.close(ps, conn);
                JDBCUtil.close(rs_1, ps_1, null);
            }
        }
        return false;
    }
}
